/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servlets;

import clases.Usuario;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 *
 * @author Miguel
 */
public class guardaFotoUsuario extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    private static final String TEMPORAL_DIR = "temp";
    private static final String DESTINO_DIR = "img/users";
    private File tmp;
    private File des;

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        // Sesion usuario
        HttpSession sesion = request.getSession();
        Usuario usu = (Usuario) sesion.getAttribute("usuario");


        // Compruebo si las carpetas existen y si no las creo
        // ************************************************************
        String ruta = getServletContext().getRealPath(TEMPORAL_DIR);
        tmp = new File(ruta);
        if (!tmp.exists()) {
            tmp.mkdir();
        }

        ruta = getServletContext().getRealPath(DESTINO_DIR);
        des = new File(ruta);
        if (!des.exists()) {
            des.mkdir();
        }

        DiskFileItemFactory dfif = new DiskFileItemFactory();
        dfif.setRepository(tmp);

        ServletFileUpload sfu = new ServletFileUpload(dfif);
        try {
            List datos = sfu.parseRequest(request);
            Iterator itr = datos.iterator();

            while (itr.hasNext()) {
                FileItem item = (FileItem) itr.next();

                if (!item.isFormField()) {
                    String[] arrStr = item.getName().split("\\\\");
                    //String nombreArchivo = arrStr[arrStr.length - 1];
                    
                    String nombreArchivo = usu.getUsuario()+".jpg";

                    File archivo = new File(des,nombreArchivo );

                    item.write(archivo);
                }
            }

        } catch (FileUploadException ex) {
            Logger.getLogger(guardaFotoUsuario.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            Logger.getLogger(guardaFotoUsuario.class.getName()).log(Level.SEVERE, null, ex);
        } finally{
                 response.sendRedirect("registro.jsp"); 
        }

        try {
            /* TODO output your page here
            out.println("<html>");
            out.println("<head>");
            out.println("<title>Servlet guardaFotoUsuario</title>");  
            out.println("</head>");
            out.println("<body>");
            out.println("<h1>Servlet guardaFotoUsuario at " + request.getContextPath () + "</h1>");
            out.println("</body>");
            out.println("</html>");
             */
        } finally {
            out.close();
        
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
